package org.sevaapp.security.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sevaapp.exception.SevaApplicationException;
import org.sevaapp.security.domain.BaseUser;
import org.sevaapp.security.domain.User;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class UserService {

	private static final Log log = LogFactory.getLog(UserService.class);

	@Autowired
	private User domainObj;

//	@Autowired
//	private Authority authDomainObj;

	/**
	 * Validation method. Every controller should implement this method
	 * to manage the data input validation in a standard and consistent way.
	 */
	public abstract boolean validate(User inputData);
	
	public BaseUser getUser (String loginId) throws SevaApplicationException {
		log.debug("getUser() method called.");
		BaseUser user = domainObj.load(loginId);
		return user;
	}

	public void addNewUser(User inputData) throws SevaApplicationException {
		log.debug("addNewUser() method called.");

		// Call validate method
		boolean isValidData = validate(inputData);
		log.debug("isValidData=" + isValidData);
		if (isValidData) {
			// Check if the user already exists
			boolean isExistingUser = false;
			String loginId = inputData.getLoginId();
			BaseUser user = getUser(loginId);
			if (user != null) {
				isExistingUser = true;
			}
			
			if (isExistingUser) {
				throw new SevaApplicationException("User id " + loginId + " already exists. Choose another name.");
			}

			// New record, call add method
			domainObj.add(inputData);
			
//			// Add new authority object
//			authDomainObj.add()
		}
	}

	public void updateUser(User inputData) {
		log.debug("addNewUser() method called.");

		// Call validate method
		boolean isValidData = validate(inputData);
		log.debug("isValidData=" + isValidData);
		if (isValidData) {
			// Existing record, call edit method
			domainObj.update(inputData);
		}
	}

}

